<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd" v-if="!selectionMaterialShow">
      <!-- 筛选按钮 -->
      <div class="search-button" v-if="!contactAddShow">
        <el-button
          v-if="pageType === 'check' && route.name === 'PaymentCheck'"
          class="btn save"
          @click="handleCheckBtn2(projectFormRef, 3, '同意')"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >同意</el-button
        >
        <el-button
          v-if="pageType === 'check' && route.name === 'PaymentCheck'"
          class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 4, '拒绝')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >拒绝</el-button
        >

        <el-button
          v-if="pageType === 'check' && route.name === 'PaymentCheck'"
          class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 6, '驳回')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >驳回</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn submit"
          @click="handleAddSave(requestFormRef, 1)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >{{ "提交" }}</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn save"
          @click="handleAddSave(requestFormRef, 0)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >存为草稿</el-button
        >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-collapse v-model="activeNames">
        <el-form
          :model="requestForm"
          ref="requestFormRef"
          :rules="queryRules"
          label-width="120px"
          v-enterToNext
          :disabled="pageType === 'detail' || pageType === 'check'"
        >
          <!-- 基础信息 -->
          <el-collapse-item
            name="1"
            v-if="!contactAddShow"
            class="transform-down"
          >
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title"
                >{{
                  pageType !== "detail" && pageType !== "check "
                    ? pageType === "add"
                      ? "新增"
                      : "编辑"
                    : ""
                }}付款申请信息</span
              >
            </template>
            <div class="request-info">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="付款编号：">
                    <el-input
                      disabled
                      v-model="requestForm.paymentApplyCode"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="关联合同：">
                    <!-- <el-select
                      v-model="requestForm.purchaseContractId"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                    >
                      <el-option
                        v-for="dict in contractList"
                        :key="dict.purchaseContractId"
                        :label="
                          dict.purchaseContractCode +
                          ' ' +
                          dict.purchaseContractName +
                          ' ' +
                          dict.distributorName
                        "
                        :value="dict.purchaseContractId"
                      />
                    </el-select> -->
                    <el-autocomplete
                      ref="contractRef"
                      popper-class="autoclass"
                      v-model="requestForm.purchaseContractCode"
                      :fetch-suggestions="querySearch"
                      placeholder="请输入"
                      @select="handleContractSelect"
                      style="width: 268px"
                      clearable
                      @clear="openInfo"
                      placement="bottom-end"
                    >
                      <template #default="{ item }">
                        <div class="auto-top" style="display: flex">
                          <div class="auto-item">合同编号</div>
                          <div class="auto-item">合同名称</div>
                          <div class="auto-item">供应商</div>
                        </div>
                        <div style="display: flex; width: 380px">
                          <div
                            class="auto-item"
                            style="text-align: left"
                            :title="item.purchaseContractCode"
                          >
                            {{ item.purchaseContractCode }}
                          </div>
                          <div
                            class="auto-item"
                            style="text-align: left"
                            :title="item.purchaseContractName"
                          >
                            {{ item.purchaseContractName }}
                          </div>
                          <div
                            class="auto-item"
                            style="text-align: left"
                            :title="item.distributorName"
                          >
                            {{ item.distributorName }}
                          </div>
                        </div>
                      </template>
                    </el-autocomplete>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请日期：" prop="applicantDate">
                    <el-date-picker
                      v-model="requestForm.applicantDate"
                      format="YYYY/MM/DD"
                      class="search-input"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请人：" prop="applicantId">
                    <el-select
                      v-model="requestForm.applicantId"
                      filterable
                      placeholder="请选择"
                      placement="bottom-end"
                      clearable
                      class="search-input"
                      @change="handleUserChange"
                    >
                      <!-- <el-option v-for="dict in userList" :key="dict.userId" :label="dict.nickName"
                        :value="dict.userId" /> -->
                      <el-option disabled :value="null">
                        <div class="auto-top">
                          <span class="auto-item">人员姓名</span>
                          <span class="auto-item">联系方式</span>
                          <span class="auto-item">职位</span>
                          <span class="auto-item">部门</span>
                        </div>
                      </el-option>
                      <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :value="dict.userId"
                        :label="dict.nickName"
                      >
                        <div style="display: flex">
                          <div class="auto-item" :title="dict.nickName">
                            {{ dict.nickName }}
                          </div>
                          <div class="auto-item" :title="dict.phonenumber">
                            {{ dict.phonenumber ? dict.phonenumber : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.postName">
                            {{ dict.postName ? dict.postName : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.fullDeptName">
                            {{ dict.fullDeptName ? dict.fullDeptName : "--" }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请部门：">
                    <el-input
                      disabled
                      v-model="requestForm.deptName"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <!-- </el-row>
              <el-row :gutter="0"> -->
                <el-col :span="6">
                  <el-form-item label="付款方式：" prop="paymentMethod">
                    <el-select
                      v-model="requestForm.paymentMethod"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                    >
                      <el-option
                        v-for="dict in wayList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="付款金额：" prop="paymentAmount">
                    <el-input
                      type="Number"
                      v-model="requestForm.paymentAmount"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="用款用途：" prop="useFunds">
                    <el-input
                      v-model="requestForm.useFunds"
                      placeholder="请列举如定金，进度款百分比，尾款、全款等"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注：">
                    <el-input
                      maxlength="2000"
                      style="width: 100%"
                      v-model="requestForm.applyRemarks"
                      type="textarea"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="合同附件：" prop="suppFileInfoVos">
                    <Upload
                      :fileList="requestForm.suppFileInfoVos"
                      :isFull="true"
                      :limit="10"
                      :showButton="true"
                      @success="(result) => uploadSuccess(result)"
                      @deleteFile="(result) => uploadRemove(result)"
                      :isCanDelete="pageType == 'detail' ? false : true"
                      :disabled="pageType == 'detail'"
                    />
                    <!-- accept=".jpg,.png" -->
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
          <!-- 基础信息 -->
          <el-collapse-item
            name="2"
            v-if="!contactAddShow"
            class="transform-down"
          >
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title">收款账户</span>
            </template>
            <div class="request-info">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="账户类型：" prop="accountType">
                    <el-select
                      v-model="requestForm.accountType"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleType"
                    >
                      <el-option
                        v-for="dict in accountTypeList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="户名：" prop="accountName">
                    <el-input
                      v-model="requestForm.accountName"
                      placeholder="真实姓名或企业名称"
                      clearable
                      class="search-input"
                      :maxlength="20"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="账号：" prop="accountCode">
                    <!-- <el-input
                      v-model="requestForm.accountCode"
                      :placeholder="!requestForm.accountType?'收款方银行账号':'手机号/邮箱'"
                      clearable
                      class="search-input"
                      :maxlength="20"
                    /> -->
                    <el-autocomplete
                      popper-class="autoclass"
                      v-model="requestForm.accountCode"
                      :fetch-suggestions="querySearch2"
                      :placeholder="
                        !requestForm.accountType
                          ? '收款方银行账号'
                          : '手机号/邮箱'
                      "
                      style="width: 268px"
                      clearable
                      :maxlength="20"
                    >
                    <template #default="{ item }">
                      <!-- <div class="auto-top"> -->
                      <div class="auto-top" style="display: flex">
                        <div class="auto-item">历史银行卡号</div>
                      </div>
                      <div style="display: flex; width: 200px">
                        <div class="auto-item" :title="item.value">
                          {{ item.value }}
                        </div>
                      
                      </div>
                    </template>
                    </el-autocomplete>
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="!requestForm.accountType">
                  <el-form-item label="银行：" prop="bankName">
                    <el-input
                      v-model="requestForm.bankName"
                      placeholder="请输入银行名称"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="!requestForm.accountType">
                  <el-form-item label="银行所在地区：" prop="city">
                    <el-select
                      filterable
                      style="width: 130px"
                      v-model="requestForm.province"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleProvince('province')"
                    >
                      <el-option
                        v-for="dict in provinceList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <el-select
                      filterable
                      style="width: 130px; margin: 0 5px"
                      v-model="requestForm.city"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleProvince('city')"
                    >
                      <el-option
                        v-for="dict in cityList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <!-- <el-select
                    filterable
                    style="width: 93px"
                    v-model="requestForm.area"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in areaList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select> -->
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="!requestForm.accountType">
                  <el-form-item label="银行支行：">
                    <el-input
                      v-model="requestForm.subBankName"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="备注：">
                    <el-input
                      maxlength="2000"
                      v-model="requestForm.bankRemarks"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-form>

        <!-- 付款列表 -->
        <el-collapse-item
          name="3"
          style="position: relative"
          :class="!contactAddShow ? 'transform-down' : ''"
          v-if="pageType === 'check'"
        >
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title">付款列表</span>
            <div
              v-if="pageType === 'check'"
              class="nofixed-search-button button-position"
            >
              <el-button class="btn save" @click.stop="handlePaySave()"
                ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
                >保存</el-button
              >
              <el-button
                class="btn add"
                @click.stop="handleContactAdd(contactFormRef)"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >添加</el-button
              >
            </div>
          </template>
          <div class="contact-info">
            <!-- 表格数据 -->
            <el-table
              :data="requestForm.payRecordInfoRespVos"
              border
              :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }"
              show-summary
              sum-text="合计"
              :summary-method="getSummaries"
            >
              <!-- 操作模式 -->
              <el-table-column
                label="操作"
                align="center"
                :show-overflow-tooltip="true"
                width="60px"
                v-if="pageType === 'check'"
              >
                <template #default="{ row, $index }">
                  <div class="table-operate">
                    <img
                      src="@/assets/icons/images/delete.png"
                      class="table-icon"
                      title="删除"
                      @click="handleOperate('delete', row, $index)"
                    />
                  </div> </template
              ></el-table-column>
              <el-table-column
                label="付款日期"
                prop="paymentDate"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label=" 经办人"
                prop="paymentUserName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="经办部门"
                prop="deptName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="实付金额（元）"
                prop="actualAmount"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row, $index }">
                  <el-input
                    v-if="pageType === 'check'"
                    type="Number"
                    v-model="row.actualAmount"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <SelectionMaterial
      ref="selectionMaterialRef"
      v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow"
      @submitChoose="handleSelectMaterial"
    />

    <el-dialog
      :title="title"
      v-model="auditDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="审核备注：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="auditRemark"
          placeholder=""
          type="textarea"
          maxlength="2000"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            v-if="auditResult == 3"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >同意</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 4"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >拒绝</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 6"
            @click="saveCheck()"
            v-loading="loadingCheck"
          >
            驳回</el-button
          >
          <el-button style="background-color: #fff" @click="closeAudit()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Picture as IconPicture } from "@element-plus/icons-vue";
import useUserStore from "@/store/modules/user";
import SelectionMaterial from "./selectionMaterial";
import Upload from "@/components/Upload/index";
import {
  getProvinceApi,
  getUserListApi,
  getDeptListApi,
  addCustomerApi,
  editCustomerApi,
  getCustomerDetailApi,
} from "@/api/information/customer";

import { getProjectListApi } from "@/api/sales/project";
import {
  addRequestApi,
  editRequestApi,
  getRequestDetailApi,
  getRequestTableApi,
} from "@/api/purchase/request";
import {
  getContractListApi,
  addPaymentApi,
  editPaymentApi,
  getPaymentDetailApi,
  checkPaymentApi,
  checkPaymentSaveApi,
  getEndFlag,
  getAccountListApi
} from "@/api/purchase/payment";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { getSupplierListApi } from "@/api/information/supplier";
const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "requestAddShow",
  // 更新客户新增组件显隐
  "update:requestAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  // 合同用印id
  contractId: {
    type: Number,
    default: null,
  },
  // 合同用印编号
  contractCode: {
    type: Number,
    default: null,
  },
});

// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const requestFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
// 新增联系人表单显隐
const contactAddShow = ref(false);
const loadingCheck = ref(false);

// 选择审核
const auditDialogShow = ref(false);
// 选择物料显隐
const selectionMaterialShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 付款方式列表
const wayList = ref([]);
// 单位列表
const unitList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 账户类型
const accountTypeList = ref([]);
// 采购合同列表
const contractList = ref([]);
// 银行账户列表
const accountList = ref([{value:'123456789'},{value:'987654321'}]);

// 客户表单数据模板
const requestFormTemplate = {
  accountCode: "", // 收款方银行账号
  accountName: "", // 银行开户名称
  accountType: 0, // 账户类型
  applicantDate: "", // 申请日期
  applicantId: null, // 申请人id
  applyRemarks: "", // 	付款申请备注
  area: null, // 区
  bankName: "", // 银行名称
  bankRemarks: "", // 银行备注
  city: null, // 市
  payRecordInfoRespVos: [], // 付款申请明细信息对象
  paymentAmount: null, // 付款金额
  paymentCheckStatus: null, // 付款申请审核状态
  paymentMethod: null, // 付款方式
  province: null, // 省
  purchaseContractId: null, // 关联采购合同id
  subBankName: "", // 银行支行名称
  suppFileInfoVos: [], // 合同附件
  type: 0, // 	按钮类型0：存为草稿；1；提交
  useFunds: "", // 用款用途
};
// 联系人表单数据模板
const contactFormTemplate = {
  actualAmount: null, // 实付金额
  paymentApplyId: null, // 	关联付款申请id
  paymentDate: "", // 	付款日期
  paymentId: null, //  付款id
  paymentUserId: null, //付款用户id
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    applicantDate: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    applicantId: [
      { required: true, message: "请选择申请人", trigger: "change" },
    ],
    purchaseContractId: [
      { required: true, message: "请选择关联合同", trigger: "change" },
    ],
    paymentMethod: [
      { required: true, message: "请选择付款方式", trigger: "change" },
    ],
    paymentAmount: [
      { required: true, message: "请输入付款金额", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value > 999999 || value < 0) {
            callback(new Error("付款金额为0到999999之间的数字"));
          } else {
            if (value.toString().split(".")[1]?.length > 2) {
              callback(new Error("付款金额小数点后最多两位"));
            } else {
              callback();
            }
          }
        },
      },
    ],
    useFunds: [{ required: true, message: "请输入用款用途", trigger: "blur" }],
    suppFileInfoVos: [
      { required: true, message: "请上传合同附件", trigger: "change" },
    ],
    accountType: [
      { required: true, message: "请选择账户类型", trigger: "change" },
    ],
    accountName: [{ required: true, message: "请输入户名", trigger: "blur" }],
    accountName: [{ required: true, message: "请输入户名", trigger: "blur" }],
    accountCode: [{ required: true, message: "请输入账号", trigger: "blur" }],
    bankName: [{ required: true, message: "请输入银行", trigger: "blur" }],
    city: [
      { required: true, message: "请选择银行所在地区", trigger: "change" },
    ],
  },
  // 联系人表单校验规则
  queryContactRules: {
    materialName: [
      { required: true, message: "请输入物料名称", trigger: "blur" },
    ],
    factoryCode: [
      { required: true, message: "请输入出厂型号", trigger: "blur" },
    ],
    technologyParameter: [
      { required: true, message: "请输入技术参数", trigger: "blur" },
    ],
    materialUnit: [
      { required: true, message: "请选择单位", trigger: "change" },
    ],
    purchaseNumber: [
      { required: true, message: "请输入请购数量", trigger: "blur" },
    ],
  },
  // 所属行业列表
  industryList: [],
  // 用户列表
  userList: [],
  // 省列表
  provinceList: [],
  // 市列表
  cityList: [],
  // 区列表
  areaList: [],
  // 用户列表
  userList: [],
  auditRemark: "",
  auditResult: "",
  applyId: "",
  endFlag: 0,
});

const {
  requestForm,
  contactForm,
  queryRules,
  queryContactRules,
  industryList,
  provinceList,
  cityList,
  areaList,
  userList,
  auditRemark,
  auditResult,
  applyId,
  endFlag,
} = toRefs(data);

const handleCheckBtn2 = (requestFormRef, type, title) => {
  auditRemark.value = "";
  if (type == 3) {
    auditRemark.value = "同意";
  }

  auditResult.value = type;
  (applyId.value = requestForm.value.paymentApplyId),
    (auditDialogShow.value = true);
  loadingCheck.value = false;
};

const saveCheck = async () => {
  if (auditRemark.value === null || auditRemark.value === "") {
    ElMessage.error("审核备注不能为空");
    return;
  }

  if (auditResult.value == 3 && endFlag.value == 1) {
    let totalMoney = 0;
    requestForm.value.payRecordInfoRespVos.forEach((item) => {
      totalMoney = totalMoney + item.actualAmount * 1;
    });
    if (totalMoney != requestForm.value.paymentAmount) {
      ElMessage.error("付款金额必须等于申请付款总额");
      return false;
    }
  }

  try {
    loadingCheck.value = true;
    requestForm.value.paymentCheckStatus = auditResult.value;
    requestForm.value.auditRemark = auditRemark.value;
    const res = await checkPaymentApi(requestForm.value);
    auditDialogShow.value = false;
    if (res.code === 200) {
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
      return;
    }
    loadingCheck.value = false;
    emit("update:requestAddShow", false);
    emit("refreshList", false);
  } catch (error) {
    loadingCheck.value = false;
  }
  ElMessage.error(error);
};

const closeAudit = () => {
  auditRemark.value = "";
  auditResult.value = "";
  applyId.value = "";
  auditDialogShow.value = false;
};

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  if (!requestFormRef) return;
  await requestFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          requestForm.value.type = type;
          let res;
          if (!requestForm.value.paymentApplyId) {
            // 新增客户
            res = await addPaymentApi(requestForm.value);
          } else {
            // 编辑客户
            res = await editPaymentApi(requestForm.value);
          }
          if (res.code === 200) {
            emit("update:requestAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:requestAddShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:requestAddShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理手动输入
 */
const handleHand = () => {
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
};

/**
 * @description: 处理选择物料
 */
const handleMaterial = () => {
  selectionMaterialShow.value = true;
};

/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value) {
    selectionMaterialShow.value = false;
    contactForm.value.materialCode = value.materialCode;
    contactForm.value.materialName = value.materialName;
    contactForm.value.factoryCode = value.factoryCode;
    contactForm.value.technologyParameter = value.technologyParameter;
    contactForm.value.materialUnit = value.materialUnit;
    contactForm.value.materialUnitName = value.materialUnitName;
    contactForm.value.supplierName = value.distributorName;
    contactForm.value.supplierId = value.supplierId;
    contactForm.value.manufacturerId = value.manufacturerId;
    contactForm.value.manufactureName = value.manufactureName;
  } else {
    ElMessage.info("请选择物料");
  }
};

/* 关联合同的下拉框 */
const contractRef = ref(null);
const openInfo = () => {
  contractRef.value.activated = true;
};

const querySearch = (queryString, cb) => {
  let results = queryString
    ? contractList.value.filter(createFilter(queryString))
    : contractList.value;
  if (queryString == "null") {
    results = contractList.value;
  }
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

/**
 * @description: 处理审核状态相关按钮
 * @param {String} type  类型
 * @param {String} title 标题
 */
const handleCheckBtn = (contractFormRef, type, title) => {
  ElMessageBox.confirm(`确定${title}以上数据吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      if (type == 3) {
        let totalMoney = 0;
        requestForm.value.payRecordInfoRespVos.forEach((item) => {
          totalMoney = totalMoney + item.actualAmount * 1;
        });
        if (totalMoney > requestForm.value.paymentAmount) {
          ElMessage.error("付款金额不能大于申请付款总额");
          return false;
        }
      }
      requestForm.value.paymentCheckStatus = type;
      const res = await checkPaymentApi(requestForm.value);
      if (res.code === 200) {
        emit("update:requestAddShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        // contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 处理类型选择
 * @param {Number} value 选择值
 */
const handleType = (value) => {
  requestForm.value.bankName = "";
  requestForm.value.subBankName = "";
  requestForm.value.province = null;
  requestForm.value.city = null;
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.dept.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 处理单位选择
 * @param {Number} value 选择值
 */
const handleUnitChange = (value) => {
  contactForm.value.materialUnitName =
    unitList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 处理付款列表保存
 */
const handlePaySave = async () => {
  // requestForm.paymentAmount

  if (!requestForm.value.payRecordInfoRespVos.length) {
    return ElMessage.warning("付款列表为空");
  }
  const hasEmptyActualAmount = requestForm.value.payRecordInfoRespVos.some(item => !item.actualAmount);
  if (hasEmptyActualAmount) {
    return ElMessage.warning("实付金额为空");
  }
  ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      const res = await checkPaymentSaveApi(requestForm.value);
      console.log("处理付款列表保存");
      console.log(res);
      if (res.code == 200) {
        ElMessage.success(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 新增、编辑联系人
 */
const handleContactAdd = async () => {
  var today = new Date();
  var year = today.getFullYear(); //获取年份
  var month = today.getMonth() + 1; //获取月份
  var day = today.getDate(); //获取日期
  let date = year + "-" + month + "-" + day;
  const userInfo = await useUserStore().getInfo();
  requestForm.value.payRecordInfoRespVos.push({
    actualAmount: null, // 实付金额
    paymentApplyId: null, // 	关联付款申请id
    paymentDate: date, // 	付款日期
    paymentId: null, //  付款id
    paymentUserName: userInfo.user.nickName, // 用户名称
    deptName: userInfo.user.dept.deptName, // 部门名称
    paymentUserId: useUserStore().id, //付款用户id
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  requestForm.value.suppFileInfoVos.push({ ...response, businessType: 11 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  requestForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理省市区操作
 * @param {String} type 类型
 */
const handleProvince = (type) => {
  switch (type) {
    case "province":
      cityList.value = [];
      areaList.value = [];
      requestForm.value.city = null;
      requestForm.value.area = null;
      getProvinceApi(requestForm.value.province).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      break;
    case "city":
      areaList.value = [];
      requestForm.value.area = null;
      getProvinceApi(requestForm.value.city).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
      break;
  }
};

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  contactAddShow.value = true;
  operateType.value = "add";
  nextTick(() => {
    refInput.value.focus();
  });
};

/**
 * @description: 联系人返回
 */
const handleRequestBack = () => {
  contactAddShow.value = false;
  nextTick(() => {
    refSelect.value.focus();
  });
};

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (column.property === "actualAmount") {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  // if (props.pageType === "add" || props.pageType === "edit") {
  //   sums[8] = sums[6] * sums[7];
  //   sums[7] = "";
  // } else {
  //   sums[7] = sums[5] * sums[6];
  //   sums[6] = "";
  // }

  return sums;
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = {
      ...JSON.parse(JSON.stringify(row)),
      suppFileInfoVos: JSON.parse(JSON.stringify(row)).suppFileInfoVos
        ? JSON.parse(JSON.stringify(row)).suppFileInfoVos
        : [],
    };
    contactForm.value.allPrice = (
      contactForm.value.purchasePrice * contactForm.value.purchaseNumber
    ).toFixed(2);
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refInput.value && refInput.value.focus(); // 聚焦
    });
  } else {
    requestForm.value.payRecordInfoRespVos.splice(tabIndex, 1);
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getPaymentDetailApi(id);
    if (res) {
      requestForm.value = {
        ...res,
        payRecordInfoRespVos: res.payApplyRecordInfoRespVos,
      };
      // 存在为null无法push场景
      if (!requestForm.value.payRecordInfoRespVos) {
        requestForm.value.payRecordInfoRespVos = [];
      }
      if (!requestForm.value.suppFileInfoVos) {
        requestForm.value.suppFileInfoVos = [];
      }
      await getProvinceApi(requestForm.value.province).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      await getProvinceApi(requestForm.value.city).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
    }

    const response = await getEndFlag(id);
    endFlag.value = response;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  
  // 历史账号
  await getAccountListApi().then((res) => {
    if (res.code === 200) {
      let arr = res.data
      accountList.value = arr.map(item => ({ value: item }));
    }
  });
  // 付款方式
  await getDictsApi("erp_payment_method").then((res) => {
    if (res.code === 200) {
      wayList.value = res.data;
    }
  });

  // 单位列表
  await getDictsApi("material_unit").then((res) => {
    if (res.code === 200) {
      unitList.value = res.data;
    }
  });

  // 账户类型
  await getDictsApi("erp_account_type").then((res) => {
    if (res.code === 200) {
      accountTypeList.value = res.data;
    }
  });

  // 供应商列表
  await getSupplierListApi().then((res) => {
    if (res.code === 200) {
      res.rows.forEach((item) => {
        item.value = item.supplierName;
      });
      suppliereList.value = res.rows;
    }
  });

  await getUserListApi({}).then((res) => {
    // if (res.code === 200) {
    //   userList.value = res.rows;
    // }
    if (res.length > 0) {
      userList.value = res;
    }
  });

  // 合同列表
  await getContractListApi().then((res) => {
    console.log("合同列表");
    console.log(res);
    if (res) {
      res.forEach((item) => {
        item.value = item.purchaseContractCode;
      });
      contractList.value = res;
    }
  });

  // 省
  await getProvinceApi(1).then((res) => {
    if (res.code === 200) {
      provinceList.value = res.data;
    }
  });

  // // 销售部门列表
  // await getDeptListApi().then((res) => {
  //   if (res.code === 200) {
  //     deptList.value = res.data;
  //     nextTick(() => {
  //       refSelect.value.focus(); // 聚焦
  //     });
  //   }
  // });
}
/**
 * @description:关联合同
 */
const handleContractSelect = (value) => {
  requestForm.value.purchaseContractId = value.purchaseContractId;
};

const querySearch2 = (queryString, cb) => {
  const results = queryString
    ? accountList.value.filter(createFilter2(queryString))
    : accountList.value;
  // if (results.length == 0) {
  //   ElMessage.info("暂无数据");
  // }
  cb(results);
};
const createFilter2 = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

onMounted(() => {
  nextTick(() => {
    requestForm.value.purchaseContractId = props.contractId;
    requestForm.value.purchaseContractCode = props.contractCode;
  });
  getDicts();
  if (props.pageType === "add") {
    nextTick(() => {
      refSelect.value && refSelect.value.focus();
    });
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;

  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }

  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }

  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }

  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
}

.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}

.auto-item {
  width: 125px;
  text-align: left;
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  /* 使用省略号表示超出部分 */
}

.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px;
  /* 设置最大高度 */
  overflow-y: auto;
  /* 超出高度时显示滚动条 */
}
:deep(.el-form-item--default) {
  margin-bottom: 22px;
}
:deep(.el-form-item--default .el-form-item__error) {
  padding-top: 5px;
}
:deep(.el-form-item--default) {
  margin-bottom: 22px;
}
:deep(.el-form-item--default .el-form-item__error) {
  padding-top: 5px;
}
</style>
